package com.example.hw_smart_home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.ContextCompat;

import com.example.hw_smart_home.huawei_api.device.*;
import com.example.hw_smart_home.huawei_api.product.ProductCommandIssued;
import com.example.hw_smart_home.huawei_api.util.Constants;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import android.graphics.drawable.GradientDrawable;

import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView deviceIStatusTextView; // 设备状态
    private ImageView deviceStatusImageView; // 设备状态图标
    private TextView temperatureTextView;   // 温度
    private ImageView temperatureImage; // 温度图片
    private TextView humidityTextView;  // 湿度
    private TextView airQualityTextView;    // 空气质量指数
    private TextView airQualityLabel;   // 空气等级
    private TextView ppmTextView;    // ppm
    private Button openDoor;    // 开门按钮
    private Button closeDoor;   // 关门按钮
    private Button openCurtain; // 开窗帘按钮
    private Button closeCurtain; // 开窗帘按钮
    private Button lightOn; // 开灯按钮
    private Button lightOff; // 开灯按钮
    private ImageView doorStateImage;   // 门开关状态图片
    private TextView doorStateTextView; // 门开关状态描述
    private ImageView curtainStateImage;    // 窗帘开关状态图片
    private TextView curtainStateTextView; // 窗帘开关描述
    private ImageView lightStateImage;  // 灯开关状态图片
    private TextView lightStateTextView;    // 灯开关描述
    private TextView doorMonitorTextView;   // 门外红外线检测
    private ImageView doorMonitorImage; // 红外线检测情况图片
    private String doorState = "OFF";   // 记录门的开关状态
    private String curtainState = "OFF";   // 记录窗帘的开关状态
    private String lightState = "OFF";  // 记录灯开关状态
    private Handler handler = new Handler();
    private Runnable queryRunnable;
    // 动态修改airQualityLabel的背景颜色
    private final List<GradientDrawable> drawablePool = new ArrayList<>(3);
    private void updateAirQualityColor(int colorResId) {
        GradientDrawable bg;
        if (!drawablePool.isEmpty()) {
            bg = drawablePool.remove(0); // 从池中复用
        } else {
            // 首次创建
            bg = (GradientDrawable) ContextCompat.getDrawable(
                    this, R.drawable.bg_air_quality
            ).mutate();
        }
        bg.setColor(ContextCompat.getColor(this, colorResId));
        airQualityLabel.setBackground(bg);
        // 用完后回收
        drawablePool.add(bg);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 组件初始化
        deviceIStatusTextView = findViewById(R.id.deviceIStatusTextView);// 设备状态
        deviceStatusImageView = findViewById(R.id.statusIcon);  // 设备状态图标
        temperatureTextView = findViewById(R.id.temperature_value);// 温度
        temperatureImage = findViewById(R.id.temperature_icon); // 温度图标
        humidityTextView = findViewById(R.id.humidity_value);// 湿度
        airQualityTextView = findViewById(R.id.air_quality_value); // 空气质量指数
        airQualityLabel = findViewById(R.id.air_quality_label);  // 空气质量等级
        ppmTextView = findViewById(R.id.air_ppm_value); // ppm
        doorStateImage = findViewById(R.id.doorStateImage);  // 门状态图片
        doorStateTextView = findViewById(R.id.doorStateTextView); // 门状态描述
        openDoor = findViewById(R.id.openDoor); // 开门按钮
        closeDoor = findViewById(R.id.closeDoor); // 关门按钮
        curtainStateImage = findViewById(R.id.curtainStateImage); // 窗帘状态图片
        curtainStateTextView = findViewById(R.id.curtainStateTextView); // 窗帘状态描述
        openCurtain = findViewById(R.id.openCurtain); // 开窗帘按钮
        closeCurtain = findViewById(R.id.closeCurtain); // 关窗帘按钮
        lightStateImage = findViewById(R.id.lightStateImage);   // 灯状态图片
        lightStateTextView = findViewById(R.id.lightStateTextView); // 灯状态描述
        lightOn = findViewById(R.id.lightOn);   // 开灯按钮
        lightOff = findViewById(R.id.lightOff); // 关灯按钮
        doorMonitorTextView = findViewById(R.id.door_monitor_text); // 门外红外线检测
        doorMonitorImage = findViewById(R.id.door_monitor_icon);    // 门外红外线情况图片

        // 设置监听器
        openDoor.setOnClickListener(this);
        closeDoor.setOnClickListener(this);
        openCurtain.setOnClickListener(this);
        closeCurtain.setOnClickListener(this);
        lightOn.setOnClickListener(this);
        lightOff.setOnClickListener(this);

        // 启动新线程进行网络调用
        queryRunnable = new Runnable() {
            @Override
            public void run() {
                // 网络请求放在线程中
                ObjectMapper objectMapper = new ObjectMapper();
                // 获取设备属性
                new Thread(() -> {
                    try {
                        // 调用已有的方法获取设备属性
                        StringBuilder deviceStatusResult = new StringBuilder();
                        String statusStr;   // 记录设备状态
                        String temperature; // 温度
                        int temperatureInt; // 温度int类型
                        String humidity;    // 湿度
                        String airQuality;  // 空气质量指数
                        String ppm; //ppm
                        String isWarning;   // 门外是否有人
                        String doorStateTemp;   // 临时记录门开关状态
                        String curtainStateTemp;    // 临时记录窗帘开关状态
                        String lightStateTemp;  // 临时记录灯开关状态
                        int colorResId; // 等级颜色

                        //设备状态
                        String deviceStatus = QueryDevice.getAttribute(Constants.PROJECT_ID_LT, Constants.DEVICE_ID_LT, Constants.DEVICE_COMMAND_URL, Constants.SERVICE_ID, Constants.NODE_ID_LT);
                        if (!deviceStatus.equals("0")) {
                            JsonNode jsonNode = objectMapper.readTree(deviceStatus);
                            statusStr = jsonNode.get("status").asText();
                            deviceStatusResult.append("设备状态: ").append(statusStr.equals("ONLINE") ? "在线" : "离线");
                        } else {
                            statusStr = "OFFLINE";
                        }
                        //温湿度 空气质量指数 PPM 门外红外线  门和窗帘状态
                        String deviceAttribute = QueryDevice.getAttribute(Constants.PROJECT_ID_LT, Constants.DEVICE_ID_LT, Constants.DEVICE_SHADOW_URL, Constants.SERVICE_ID, Constants.NODE_ID_LT);
                        if (!deviceAttribute.equals("0")) {
                            JsonNode jsonNode = objectMapper.readTree(deviceAttribute)
                                    .get("shadow").get(0).get("reported").get("properties");
                            System.out.println(objectMapper.readTree(deviceAttribute).get("shadow"));
                            System.out.println(jsonNode);
                            // 获取温度
                            if (jsonNode.has("Temperature")) {
                                temperatureInt = jsonNode.get("Temperature").asInt();
                                temperature = temperatureInt + "°C";
                            } else {
                                temperature = "--";
                                temperatureInt = 26;
                            }
                            // 获取湿度
                            if (jsonNode.has("Humidity")) {
                                humidity = jsonNode.get("Humidity").asText() + "%";
                            } else {
                                humidity = "--";
                            }
                            // 获取空气指数
                            if (jsonNode.has("Air_Quality")) {
                                String airQualityTemp = "AQI:" + jsonNode.get("Air_Quality").asText();
                                int airQualityInt = Integer.parseInt(jsonNode.get("Air_Quality").asText());
                                // 对空气质量等级进行划分
                                if (airQualityInt <= 50) {
                                    colorResId = R.color.green;
                                    airQuality = airQualityTemp + "(优)";
                                } else if (airQualityInt <= 100) {
                                    colorResId = R.color.yellow;
                                    airQuality = airQualityTemp + "(良)";
                                } else if (airQualityInt <= 150) {
                                    colorResId = R.color.orange;
                                    airQuality = airQualityTemp + "(轻度污染)";
                                } else if (airQualityInt <= 200) {
                                    colorResId = R.color.red;
                                    airQuality = airQualityTemp + "(中度污染)";
                                } else if (airQualityInt <= 300) {
                                    colorResId = R.color.purple;
                                    airQuality = airQualityTemp + "(重度污染)";
                                } else {
                                    colorResId = R.color.brown_red;
                                    airQuality = airQualityTemp + "(严重污染)";
                                }
                            } else {
                                airQuality = "AQI:--";
                                colorResId = R.color.white;
                            }
                            // 获取ppm
                            if (jsonNode.has("PPM")) {
                                ppm = "PPM: " + jsonNode.get("PPM").asText();
                            } else {
                                ppm = "PPM: --";
                            }
                            // 获取门外红外线状态
                            if (jsonNode.has("Doorway")) {
                                isWarning = jsonNode.get("Doorway").asText();
                            } else {
                                isWarning = "false";
                            }
                            // 获取门开关状态
                            if (jsonNode.has("Door_State")) {
                                doorStateTemp = jsonNode.get("Door_State").asText();
                            } else {
                                doorStateTemp = doorState;
                            }
                            // 获取窗帘开关状态
                            if (jsonNode.has("Curtain_State")) {
                                curtainStateTemp = jsonNode.get("Curtain_State").asText();
                            } else {
                                curtainStateTemp = curtainState;
                            }
                            // 获取灯开关状态
                            if (jsonNode.has("Light")) {
                                lightStateTemp = jsonNode.get("Light").asText();
                            } else {
                                lightStateTemp = lightState;
                            }
                        } else {
                            temperature = "--";
                            temperatureInt = 26;
                            humidity = "--";
                            airQuality = "AQI:--";
                            ppm = "PPM: --";
                            colorResId = R.color.green;
                            isWarning = "false";
                            doorStateTemp = doorState;
                            curtainStateTemp = curtainState;
                            lightStateTemp = lightState;
                        }
                        // 更新 UI
                        Handler mainHandler = new Handler(Looper.getMainLooper());
                        mainHandler.post(() -> {
                            deviceIStatusTextView.setText(deviceStatusResult);
                            if (statusStr.equals("ONLINE")) {
                                deviceStatusImageView.setImageResource(R.drawable.online);
                            } else {
                                deviceStatusImageView.setImageResource(R.drawable.offline);
                            }
                            temperatureTextView.setText(temperature);
                            if (temperatureInt < 18) {
                                temperatureImage.setImageResource(R.drawable.temperature_cold);
                            } else if (temperatureInt <= 26) {
                                temperatureImage.setImageResource(R.drawable.temperature);
                            } else if (temperatureInt <= 30) {
                                temperatureImage.setImageResource(R.drawable.temperature_hot);
                            } else {
                                temperatureImage.setImageResource(R.drawable.temperature_sohot);
                            }
                            humidityTextView.setText(humidity);
                            airQualityTextView.setText(airQuality);
                            updateAirQualityColor(colorResId);
                            ppmTextView.setText(ppm);
                            if (isWarning.equals("true")) {
                                doorMonitorTextView.setText("门外状态: 有人");
                                doorMonitorImage.setImageResource(R.drawable.warning);
                            } else {
                                doorMonitorTextView.setText("门外状态: 正常");
                                doorMonitorImage.setImageResource(R.drawable.normal);
                            }
                            if (!doorState.equals(doorStateTemp)) { // 门状态发生改变
                                doorState = doorStateTemp;
                                if (doorState.equals("ON")) {
                                    doorStateImage.setImageResource(R.drawable.open_door);
                                    doorStateTextView.setText("门状态: 开");
                                    Toast.makeText(MainActivity.this, "门已开", Toast.LENGTH_SHORT).show();
                                } else {
                                    doorStateImage.setImageResource(R.drawable.close_door);
                                    doorStateTextView.setText("门状态: 关");
                                    Toast.makeText(MainActivity.this, "门已关", Toast.LENGTH_SHORT).show();
                                }
                            }
                            if (!curtainState.equals(curtainStateTemp)) {   // 窗帘状态发生改变
                                curtainState = curtainStateTemp;
                                if (curtainState.equals("ON")) {
                                    curtainStateImage.setImageResource(R.drawable.open_curtain);
                                    curtainStateTextView.setText("窗帘状态: 开");
                                    Toast.makeText(MainActivity.this, "窗帘已开", Toast.LENGTH_SHORT).show();
                                } else {
                                    curtainStateImage.setImageResource(R.drawable.close_curtain);
                                    curtainStateTextView.setText("窗帘状态: 关");
                                    Toast.makeText(MainActivity.this, "窗帘已关", Toast.LENGTH_SHORT).show();
                                }
                            }
                            if (!lightState.equals(lightStateTemp)) {   // 灯状态发生改变
                                lightState = lightStateTemp;
                                if (lightState.equals("ON")) {
                                    lightStateImage.setImageResource(R.drawable.on_light);
                                    lightStateTextView.setText("灯状态: 开");
                                    Toast.makeText(MainActivity.this, "灯已开", Toast.LENGTH_SHORT).show();
                                } else {
                                    lightStateImage.setImageResource(R.drawable.off_light);
                                    lightStateTextView.setText("灯状态: 关");
                                    Toast.makeText(MainActivity.this, "灯已关", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> deviceIStatusTextView.setText("查询失败: " + e.getMessage()));
                    }
                }).start();
                // 设置每 3 秒查询一次
                handler.postDelayed(this, 3000);
            }
        };
        // 启动定时查询
        handler.post(queryRunnable);
    }

    // 发送命令
    public void sendCommand(String command, Map<String, Object> paras) throws Exception {
        ProductCommandIssued.issueCommand(command, Constants.SERVICE_ID, paras);
    }

    // 监听事件触发时所执行的操作
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        new Thread(() -> {
            try {
                if (viewId == R.id.lightOn && !lightState.equals("ON")) {
                    sendCommand("light", new HashMap<>(Map.of("control", "ON")));
                } else if (viewId == R.id.lightOff && !lightState.equals("OFF")) {
                    sendCommand("light", new HashMap<>(Map.of("control", "OFF")));
                } else if (viewId == R.id.openDoor && !doorState.equals("ON")) {
                    sendCommand("door", new HashMap<>(Map.of("control", "ON")));
                } else if (viewId == R.id.closeDoor && !doorState.equals("OFF")) {
                    sendCommand("door", new HashMap<>(Map.of("control", "OFF")));
                } else if (viewId == R.id.openCurtain && !curtainState.equals("ON")) {
                    sendCommand("curtain", new HashMap<>(Map.of("control", "ON")));
                } else if (viewId == R.id.closeCurtain && !curtainState.equals("OFF")) {
                    sendCommand("curtain", new HashMap<>(Map.of("control", "OFF")));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        // 解绑监听器
        openDoor.setOnClickListener(null);
        closeDoor.setOnClickListener(null);
        openCurtain.setOnClickListener(null);
        openCurtain.setOnClickListener(null);
        lightOn.setOnClickListener(null);
        lightOff.setOnClickListener(null);
        super.onDestroy();
        // 清除定时任务，避免内存泄漏
        handler.removeCallbacks(queryRunnable);
    }
}